package com.news.controller;


import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.news.common.lang.Const;
import com.news.common.lang.Result;
import com.news.entity.SysAdmin;
import com.news.service.SysAdminService;
import com.news.utils.JWTUtils;
import com.news.vo.LoginVo;
import com.news.vo.PasswordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Leeion
 * @since 2021-12-06
 */
@RestController
public class SysAdminController{

    //管理员
    @Autowired
    SysAdminService sysAdminService;

    //redis缓存
//    @Autowired
//    RedisTemplate<String, String> redisTemplate;

    @PostMapping("/admin")
    public Result login(@Validated @RequestBody LoginVo loginVo, HttpServletResponse respone){
        //断言判断用户
        SysAdmin sysAdmin = sysAdminService.getOne(new QueryWrapper<SysAdmin>().eq("username",loginVo.getUsername()));
        Assert.notNull(sysAdmin,"管理员不存在");

        if(!sysAdmin.getPassword().equals(SecureUtil.md5(loginVo.getPassword()+Const.SALT))){
            return Result.fail("密码不正确");
        }
        String token = JWTUtils.createToken(sysAdmin.getId());
        respone.setHeader("Authorization",token);
        respone.setHeader("Access-control-Expose-Headers","Authorization");

        return Result.succ(MapUtil.builder()
                .put("id",sysAdmin.getId())
                .put("username",sysAdmin.getUsername())
                .put("avatar",sysAdmin.getAvatar())
                .map()
        );
    }

    //事务回滚注解
    @Transactional
    //修改密码接口
    @PostMapping("/sys/admin/updatePass")
    public Result updatePass(@Validated @RequestBody PasswordVo passwordVo){
        SysAdmin sysAdmin = sysAdminService
                .getOne(new QueryWrapper<SysAdmin>()
                .eq("password",SecureUtil.md5(passwordVo.getCurrentPass()+Const.SALT)));
        Assert.notNull(sysAdmin,"旧密码不正确");
        sysAdmin.setPassword(SecureUtil.md5(passwordVo.getPassword()+Const.SALT));
        sysAdmin.setUpdateTime(LocalDateTime.now());
        sysAdminService.updateById(sysAdmin);
        return Result.succ("");
    }
}
